package com.rh.number.controller;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rh.number.Converter.SqlDateConverter;
import com.rh.number.dto.ExcelExportParam;
import com.rh.number.entity.numberEntity; // 注意：建议改为大驼峰命名NumberEntity
import com.rh.number.listener.NumberImportListener;
import com.rh.number.service.NumberService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/excel")
public class ExcelController {

    private final NumberService numberService;
    private final ObjectMapper objectMapper;

    @Autowired
    public ExcelController(NumberService numberService, ObjectMapper objectMapper) {
        this.numberService = numberService;
        this.objectMapper = objectMapper;
    }

    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importNumbers(@RequestParam("file") MultipartFile file) {
        try {
            NumberImportListener listener = new NumberImportListener(numberService);
            EasyExcel.read(file.getInputStream(), numberEntity.class, listener).sheet().doRead();

            Map<String, Object> result = listener.getImportResult();
            result.put("code", 200);
            result.put("msg", "导入完成");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "code", 500,
                    "msg", "导入失败: " + e.getMessage()
            ));
        }
    }


    //导出接口
    @PostMapping("/export")
    public void exportNumbers(
            @RequestBody(required = false) ExcelExportParam condition, // 直接接收查询条件
            HttpServletResponse response
    ) throws IOException {
        try {
            // 事务边界开始
            List<numberEntity> data = numberService.exportExcel(condition);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("号码数据导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName + ".xlsx");

            // 流式写入Excel
            try (OutputStream out = response.getOutputStream()) {
                EasyExcel.write(out, numberEntity.class)
                        .registerConverter(new SqlDateConverter())
                        .sheet("数据")
                        .doWrite(data);
            }

        } catch (Exception e) {
            // 统一错误处理
            response.reset();
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(
                    Map.of(
                            "code", 500,
                            "msg", "导出失败: " + e.getMessage(),
                            "timestamp", LocalDateTime.now()
                    )
            ));
        }
    }

    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 1. 从 resources 目录加载模板文件
        ClassPathResource resource = new ClassPathResource("templates/号码模板.xlsx");

        // 2. 检查文件是否存在
        if (!resource.exists()) {
            response.sendError(404, "模板文件未找到");
            return;
        }

        // 3. 设置响应头
        String fileName = URLEncoder.encode("号码模板.xlsx", StandardCharsets.UTF_8);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment;filename=" + fileName);

        // 4. 将文件流写入响应
        try (InputStream inputStream = resource.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {
            StreamUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            response.reset();
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("utf-8");
            response.getWriter().println("{\"code\":500,\"msg\":\"模板下载失败\"}");
        }
    }

    // 抽取公共错误处理方法
    private void handleExportError(HttpServletResponse response, Exception e) throws IOException {
        response.reset();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");

        Map<String, Object> error = new HashMap<>();
        error.put("code", e instanceof IllegalArgumentException ? 400 : 500);
        error.put("msg", e.getMessage());
        error.put("data", null);

        response.getWriter().println(objectMapper.writeValueAsString(error));
    }
    //批量导出
    @PostMapping("/by-ids")
    public void exportByIds( @RequestBody Map<String, List<Integer>> request,
                            HttpServletResponse response) throws IOException {
        try {
            // 1. 获取数据
            List<Integer> ids = request.get("ids");
            List<numberEntity> data = numberService.batchExportByIds(ids);

            // 2. 配置响应头
            String fileName = URLEncoder.encode("号码数据导出", StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
            response.setCharacterEncoding("UTF-8");

            // 3. 写入Excel
            EasyExcel.write(response.getOutputStream(), numberEntity.class)
                    .autoCloseStream(true)
                    .sheet("号码数据")
                    .doWrite(data);

        } catch (Exception e) {
            // 错误处理
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println("{\"code\":500,\"msg\":\"" + e.getMessage() + "\"}");
        }
    }
}